package hongcaosp.app.android.video.player;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.tencent.liteav.basic.log.TXCLog;
import com.tencent.liteav.demo.play.SuperPlayerConst;
import com.tencent.liteav.demo.play.SuperPlayerGlobalConfig;
import com.tencent.liteav.demo.play.SuperPlayerModel;
import com.tencent.liteav.demo.play.bean.TCPlayInfoStream;
import com.tencent.liteav.demo.play.common.TCPlayerConstants;
import com.tencent.liteav.demo.play.net.LogReport;
import com.tencent.liteav.demo.play.net.SuperVodInfoLoader;
import com.tencent.liteav.demo.play.net.TCHttpURLClient;
import com.tencent.liteav.demo.play.utils.PlayInfoResponseParser;
import com.tencent.liteav.demo.play.utils.SuperPlayerUtil;
import com.tencent.liteav.demo.play.view.TCDanmuView;
import com.tencent.liteav.demo.play.view.TCVideoQulity;
import com.tencent.liteav.txcvodplayer.TextureRenderView;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXBitrateItem;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXVodPlayConfig;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;

import hongcaosp.app.android.R;

/**
 * Created by liyuejiao on 2018/7/3.
 */

public class SimplePlayerView extends TXCloudVideoView implements ITXVodPlayListener {
    private static final String TAG = "SimplePlayerView";
    private Context mContext;

    private int mPlayMode = SuperPlayerConst.PLAYMODE_WINDOW;
    private boolean mLockScreen = false;

    // UI
    private TXCloudVideoView mTXCloudVideoView;

    // 点播播放器
    private TXVodPlayer mVodPlayer;
    private TXVodPlayConfig mVodPlayConfig;
    private PlayerStateListener mPlayerStateListener;

    private int mCurrentPlayState = SuperPlayerConst.PLAYSTATE_PLAY;
    private boolean mDefaultSet;
    private SuperPlayerModel mCurrentSuperPlayerModel;
    private boolean mIsMultiBitrateStream;
    private boolean mIsPlayWithFileid;

    private boolean mIsLoop;

    public SimplePlayerView(Context context) {
        super(context);
        initView(context);
    }

    public SimplePlayerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private void initView(Context context) {
        mContext = context;
        mTXCloudVideoView = this;
    }

    public void setIsLoop(boolean isLoop) {
        this.mIsLoop = isLoop;
    }

    /**
     * 初始化点播播放器
     *
     * @param context
     */
    private void initVodPlayer(Context context) {
        if (mVodPlayer != null) {
            return;
        }

        mVodPlayer = new TXVodPlayer(context);
        mVodPlayer.setLoop(mIsLoop);
        SuperPlayerGlobalConfig config = SuperPlayerGlobalConfig.getInstance();
        if (fullScreen) {
            config.renderMode = TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN;
        } else {
            config.renderMode = TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION;
        }
        config.maxCacheItem = 20;

        mVodPlayConfig = new TXVodPlayConfig();
        mVodPlayConfig.setCacheFolderPath(Environment.getExternalStorageDirectory().getPath() + "/redgrass");
        mVodPlayConfig.setMaxCacheItems(config.maxCacheItem);

        mVodPlayer.setConfig(mVodPlayConfig);
        mVodPlayer.setRenderMode(config.renderMode);
        mVodPlayer.setVodListener(this);
        mVodPlayer.enableHardwareDecode(config.enableHWAcceleration);
    }

    private boolean fullScreen = true;

    public void setFullScreen(boolean fullScreen) {
        this.fullScreen = fullScreen;
    }

    /**
     * 播放一个点播
     *
     * @param superPlayerModel
     */
    public void prepareWithMode(SuperPlayerModel superPlayerModel,boolean autoPlay) {
        initVodPlayer(getContext());
        stopPlay();
        mVodPlayer.setPlayerView(this);

        if (!TextUtils.isEmpty(superPlayerModel.videoURL)) {
            playWithURL(superPlayerModel,autoPlay);
        } else {
            playWithFileId(superPlayerModel,autoPlay);
        }
    }

    /**
     * 播放点播
     *
     * @param superPlayerModel
     */
    private void playWithURL(SuperPlayerModel superPlayerModel,boolean autoPlay) {
        mCurrentSuperPlayerModel = superPlayerModel;
        TXCLog.i(TAG, "playWithURL videoURL:" + superPlayerModel.videoURL);
        String videoURL = parseVodURL(superPlayerModel);

        if (videoURL.endsWith(".m3u8")) {
            mIsMultiBitrateStream = true;
        }
        if (mVodPlayer != null) {
            mDefaultSet = false;
            mVodPlayer.setAutoPlay(autoPlay);
            mVodPlayer.setVodListener(this);
            int ret = mVodPlayer.startPlay(videoURL);
            if (ret == 0) {
//                mCurrentPlayState = SuperPlayerConst.PLAYSTATE_PLAY;
                TXCLog.e(TAG, "playWithURL mCurrentPlayState:" + mCurrentPlayState);
            }
        }
        mIsPlayWithFileid = false;
    }

    public void setPlayerStateListener(PlayerStateListener playerStateListener) {
        this.mPlayerStateListener = playerStateListener;
    }

    /**
     * 解析点播地址
     *
     * @param superPlayerModel
     * @return
     */
    private String parseVodURL(SuperPlayerModel superPlayerModel) {
        return superPlayerModel.videoURL;
    }

    /**
     * 播放点播fileId
     *
     * @param superPlayerModel
     */
    private void playWithFileId(final SuperPlayerModel superPlayerModel,final boolean autoPlay) {
        SuperVodInfoLoader loader = new SuperVodInfoLoader();
        loader.setOnVodInfoLoadListener(new SuperVodInfoLoader.OnVodInfoLoadListener() {
            @Override
            public void onSuccess(PlayInfoResponseParser response) {
                SuperPlayerModel playerModel = new SuperPlayerModel();
                TCPlayInfoStream masterPlayList = response.getMasterPlayList();
                playerModel.imageInfo = response.getImageSpriteInfo();
                playerModel.keyFrameDescInfos = response.getKeyFrameDescInfos();
                if (masterPlayList != null) { //有masterPlaylist
                    String videoURL = masterPlayList.getUrl();
                    playerModel.videoURL = videoURL;
                    playWithURL(playerModel,autoPlay);
                    mIsMultiBitrateStream = true;
                    mIsPlayWithFileid = true;
                    return;
                }

                LinkedHashMap<String, TCPlayInfoStream> transcodeList = response.getTranscodePlayList();
                if (transcodeList != null && transcodeList.size() != 0) { //没有transcodePlaylist
                    String defaultClassification = response.getDefaultVideoClassification();
                    TCPlayInfoStream stream = transcodeList.get(defaultClassification);
                    String videoURL = stream.getUrl();
                    playerModel.videoURL = videoURL;
                    playWithURL(playerModel,autoPlay);
                    mIsMultiBitrateStream = false;
                    mIsPlayWithFileid = true;
                    return;
                }
                TCPlayInfoStream sourceStream = response.getSource();
                if (sourceStream != null) {
                    String videoURL = sourceStream.getUrl();
                    playerModel.videoURL = videoURL;
                    playWithURL(playerModel,autoPlay);
                    String defaultClassification = response.getDefaultVideoClassification();

                    if (defaultClassification != null) {
                        TCVideoQulity defaultVideoQulity = SuperPlayerUtil.convertToVideoQuality(sourceStream, defaultClassification);

                        ArrayList<TCVideoQulity> videoQulities = new ArrayList<>();
                        videoQulities.add(defaultVideoQulity);
                        mIsMultiBitrateStream = false;
                    }
                }

            }

            @Override
            public void onFail(int errCode) {

            }
        });
        loader.getVodByFileId(superPlayerModel);
    }

    public boolean isPlaying() {
        if (mVodPlayer != null) {
            return mVodPlayer.isPlaying();
        }
        return false;
    }

    public void onResume() {
        if (mVodPlayer != null) {
            mVodPlayer.resume();
            if (mPlayerStateListener != null) {
                mPlayerStateListener.onStart();
            }
        }
    }

    public void onPause() {
        if (mVodPlayer != null) {
            mVodPlayer.pause();
            if (mPlayerStateListener != null) {
                mPlayerStateListener.onPause();
            }
        }
        TXCLog.e(TAG, "pause mCurrentPlayState");
    }

    public void resetPlayer() {
        stopPlay();
    }

    public void stopPlay() {
        if (mVodPlayer != null) {
            mVodPlayer.setVodListener(null);
            mVodPlayer.stopPlay(false);
        }
        if (mPlayerStateListener != null) {
            mPlayerStateListener.onStop();
        }
        TXCLog.e(TAG, "stopPlay mCurrentPlayState");
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }

        return super.equals(obj);
    }

    /**
     * 点播播放器回调
     *
     * @param player
     * @param event  事件id.id类型请参考 {@linkplain TXLiveConstants#PLAY_EVT_CONNECT_SUCC 播放事件列表}.
     * @param param
     */
    @Override
    public void onPlayEvent(TXVodPlayer player, int event, Bundle param) {
        if (event != TXLiveConstants.PLAY_EVT_PLAY_PROGRESS) {
            String playEventLog = "TXVodPlayer onPlayEvent event: " + event + ", " + param.getString(TXLiveConstants.EVT_DESCRIPTION);
            TXCLog.d(TAG, playEventLog);
        }

        if (event == TXLiveConstants.PLAY_EVT_PLAY_BEGIN) {
            if (mPlayerStateListener != null)mPlayerStateListener.onStart();
        } else if (event == TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED) { //视频准备好
            if (mPlayerStateListener != null)mPlayerStateListener.onPrepare();
            if (mIsMultiBitrateStream) {
                ArrayList<TXBitrateItem> bitrateItems = mVodPlayer.getSupportedBitrates();

                if (bitrateItems == null || bitrateItems.size() == 0)
                    return;
                Collections.sort(bitrateItems); //masterPlaylist多清晰度，按照码率排序，从低到高

                ArrayList<TCVideoQulity> videoQulities = new ArrayList<>();
                int size = bitrateItems.size();
                for (int i = 0; i < size; i++) {
                    TXBitrateItem bitrateItem = bitrateItems.get(i);
                    TCVideoQulity quality = SuperPlayerUtil.convertToVideoQuality(bitrateItem, i);
                    videoQulities.add(quality);
                }

                if (!mDefaultSet) {
                    TXBitrateItem defaultitem = bitrateItems.get(bitrateItems.size() - 1);
                    mVodPlayer.setBitrateIndex(defaultitem.index); //默认播放码率最高的
                    // 180x320 流畅, 360x640 标清, 720x1280 高清
                    mDefaultSet = true;
                }
            }
        }  else if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {
            if (mPlayerStateListener != null)mPlayerStateListener.onPause();
        } else if (event == TXLiveConstants.PLAY_EVT_PLAY_PROGRESS) {
            int progress = param.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS);
            int duration = param.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS);
            if (mPlayerStateListener != null)mPlayerStateListener.onPlayProgress(progress,duration);
        } else if (event == TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME) {
            if (mPlayerStateListener != null)mPlayerStateListener.onFirstFrame();
        } else if (event == TXLiveConstants.PLAY_EVT_PLAY_LOADING) {
            if (mPlayerStateListener != null)mPlayerStateListener.onLoading();
        } else if (event == TXLiveConstants.PLAY_EVT_VOD_LOADING_END) {
            if (mPlayerStateListener != null)mPlayerStateListener.onLoadEnd();
        }
        if (event < 0) {
            mVodPlayer.stopPlay(true);
            if (mPlayerStateListener != null)mPlayerStateListener.onFailed(param.getString(TXLiveConstants.EVT_DESCRIPTION));
        }
    }

    @Override
    public void onNetStatus(TXVodPlayer player, Bundle status) {

    }

    /**
     * 获取当前播放模式
     *
     * @return
     */
    public int getPlayMode() {
        return mPlayMode;
    }

    /**
     * 获取当前播放状态
     *
     * @return
     */
    public int getPlayState() {
        return mCurrentPlayState;
    }

    public boolean isCover() {
        boolean cover = false;
        Rect rect = new Rect();
        cover = getGlobalVisibleRect(rect);
        if (cover) {
            if (rect.width() >= getMeasuredWidth() && rect.height() >= getMeasuredHeight()) {
                return !cover;
            }
        }
        return true;
    }

    public void release() {
        // 释放网络请求资源
        TCHttpURLClient.getInstance().release();
    }

   public interface PlayerStateListener {
        void onPrepare();
        void onStart();
        void onPause();
        void onStop();
        void onPlayProgress(int progress,int duration);
        void onFirstFrame();
        void onLoading();
        void onLoadEnd();
        void onFailed(String message);
    }
}
